<template>
	<view class="container">
		<!-- 导航栏 -->
		<view class="navTop">
			<u-navbar title="企业信息编辑" title-color="#333" bg-color="#fff" :is-back="true"></u-navbar>
		</view>

		<!-- 主要内容 -->
		<scroll-view scroll-y class="results-scroll " :style="{height: swiperHeight - 10 + 'px'}" enhanced
			show-scrollbar="{{false}}" v-if="formConfig">
			<view class="content ">
				<u-form :model="companyForm" ref="companyForm" label-width="150">
					<view class="formItem" v-for="category in groupedFields" :key="category.name">
						<u-section color="#2979ff" :title="category.name" :right="false"></u-section>
						<view class="section ">
							<view class="section-item " v-for="field in category.fields" :key="field.key">
								<!-- 图片上传字段 -->
								<view class="img-upload " v-if="field.renderType === 'img'">
									<view class="section-title ">{{field.label}}</view>
									<view class="img-container " @click="chooseLogoImage(field.key)">
										<image v-if="companyForm[field.key]" :src="companyForm[field.key]"
											mode="aspectFill" class="logo-image" />
										<view v-else class="upload-btn">
											<u-icon name="plus" size="40" color="#ccc"></u-icon>
											<text class="upload-text">上传{{field.label}}</text>
										</view>
										<view v-if="uploading" class="upload-mask">
											<u-loading mode="circle" color="#fff"></u-loading>
											<text class="mask-text">上传中...</text>
										</view>
									</view>
									<text class="img-tip ">建议尺寸：300×300像素，支持JPG/PNG格式</text>
									<u-icon v-if="companyForm[field.key]" name="trash" size="32" color="#f56c6c"
										@click="deleteLogo(field.key)" class="delete-icon"></u-icon>
								</view>

								<!-- 标签数组字段 -->
								<view class="strArrForm " v-else-if="field.renderType === 'strArr'">
									<u-form-item :label="field.label" :key="field.key" :required="field.required">
										<view class="tags-container">
											<view class="tags-list">
												<u-tag
													v-for="(item, index) in getArrayFromString(companyForm[field.key])"
													:key="index" :text="item" type="success" shape="circleRight"
													closeable @close="removeTag(field.key, field.label, index)"
													@click="editTag(index, field.label, field.key, item)"
													class="tag-item">
												</u-tag>
											</view>
											<view class="add-tag" @click="showTagDialog(field.label, field.key)">
												<u-icon name="plus" size="28" color="#2979ff"></u-icon>
												<text>添加{{field.label}}</text>
											</view>
										</view>
									</u-form-item>
								</view>

								<!-- 对象数组字段 -->
								<view class="objArr " v-else-if="field.renderType === 'objArr'">
									<view class="obj-list">
										<view class="obj-card" v-for="(objContent, index) in companyForm[field.key]"
											:key="index">
											<view class="obj-content">
												<view class="info">
													<view :class="subField.key" v-for="subField in field.formConfig"
														:key="subField.key">
														{{objContent[subField.key]}}
													</view>
												</view>
												<view class="operate">
													<view class="up">
														<u-icon name="trash" size="36" color="#f56c6c"
															@click="showDeleteConfirm(index, field.label, field.key)"></u-icon>
														<u-icon name="edit-pen-fill" size="36" color="#2979ff"
															@click="editItem(index, objContent, field.key, field.label, field.formConfig)"></u-icon>
													</view>
												</view>
											</view>
										</view>
										<view class="add-card"
											@click="showItemDialog(field.label, field.key, field.formConfig)">
											<u-icon name="plus" size="36" color="#2979ff"></u-icon>
											<text>添加{{field.label}}</text>
										</view>
									</view>
								</view>

								<!-- 数字输入字段 -->
								<u-form-item v-else-if="field.renderType === 'number'" :label="field.label"
									:prop="field.key" :required="field.required">
									<view class="numberBox">
										<u-input type="number" v-model.number="companyForm[field.key]"
											:placeholder="field.placeholderTemplate||'请输入'" />
										<u-tag type="success" :text="field.unit"></u-tag>
									</view>
								</u-form-item>

								<!-- 文本域字段 -->
								<u-form-item v-else-if="field.renderType === 'textarea'" :label="field.label"
									:prop="field.key" :required="field.required">
									<u-input type="textarea" height="80" v-model="companyForm[field.key]"
										:placeholder="field.placeholderTemplate||'请输入'" />
								</u-form-item>

								<!-- 默认文本输入字段 -->
								<u-form-item v-else :label="field.label" :prop="field.key" :required="field.required">
									<u-input type="text" v-model="companyForm[field.key]"
										:placeholder="field.placeholderTemplate||'请输入'" />
								</u-form-item>
							</view>
						</view>
					</view>
				</u-form>
			</view>
		</scroll-view>

		<!-- 标签编辑弹窗 -->
		<u-modal v-model="showTagDialogVisible" :title="tagDialogTitle" :show-cancel-button="true" @confirm="showTagDialogVisible = saveTag() ? false : true"
			@cancel="resetTagForm" width="90%">
			<view class="form">
				<u-form-item :label="currentTagLabel" label-width="150">
					<u-input v-model="currentTagValue" :placeholder="`请输入${currentTagLabel}`" />
				</u-form-item>
			</view>
		</u-modal>

		<!-- 对象编辑弹窗 -->
		<u-modal v-model="showItemDialogVisible" :title="itemDialogTitle" :show-cancel-button="true" @confirm="showItemDialogVisible = saveTag() ? false : true"
			@cancel="resetItemForm" width="90%">
			<view class="form">
				<u-form-item :label="item.label" label-width="150" v-for="(item, index) in currentFormConfig"
					:key="index" :required="item.required">
					<u-input v-model="currentItem[item.key]" :type="item.inputType"
						:placeholder="item.placeholderTemplate||'请输入'" />
				</u-form-item>
			</view>
		</u-modal>

		<!-- 删除确认弹窗 -->
		<u-modal v-model="showDeleteDialogVisible" title="提示" :content="deleteConfirmText" :show-cancel-button="true"
			@confirm="confirmDelete"></u-modal>

		<!-- 底部保存按钮 -->
		<view class="footer">
			<u-button type="primary" :ripple="true" shape="circle" @click="saveCompanyInfo"
				:loading="saving">{{ saving ? '保存中...' : '保存信息' }}</u-button>
		</view>
	</view>
</template>

<script>
	import {
		toast,
		toastC,
		showConfirm,
		toastload,
		closeload
	} from "../../utils/common"
	import {
		removeToken
	} from '@/utils/auth'
	import {
		getCompanyInfo,
		customerUpdate,
		getColumns
	} from "@/api/index.js"

	export default {
		data() {
			return {
				// UI状态
				uploading: false,
				saving: false,
				swiperHeight: 0,

				// 表单数据
				formConfig: [],
				companyForm: {},

				// 标签相关
				showTagDialogVisible: false,
				tagDialogTitle: "",
				currentTagLabel: "",
				currentTagValue: "",
				currentTagKey: "",
				currentTagIndex: -1,

				// 对象相关
				showItemDialogVisible: false,
				itemDialogTitle: "",
				currentFormConfig: [],
				currentItem: {},
				currentItemKey: "",
				currentItemIndex: -1,

				// 删除相关
				showDeleteDialogVisible: false,
				deleteConfirmText: "",
				deleteIndex: -1,
				deleteKey: ""
			}
		},

		computed: {
			// 按分类分组字段
			groupedFields() {
				const fields = this.formConfig.filter(field => field.isShow && field.key !== "operation")
				const categories = new Map()

				fields.forEach(field => {
					if (!categories.has(field.category)) {
						categories.set(field.category, [])
					}
					categories.get(field.category)?.push(field)
				})

				return Array.from(categories.entries()).map(([name, fields]) => ({
					name,
					fields
				}))
			}
		},
		onLoad() {
			this.loadCompanyInfo()
		},

		onReady() {
			this.$nextTick(() => {
				this.initBoxSize()
			})
		},

		methods: {
			// 初始化视图高度
			async initBoxSize() {
				try {
					const [navH, boxH, footerH] = await Promise.all([
						this.measureHeight('.navTop'),
						this.measureHeight('.container'),
						this.measureHeight('.footer')
					])
					this.swiperHeight = boxH - navH - footerH
				} catch (error) {
					console.error("高度计算错误:", error)
					this.swiperHeight = 300
				}
			},

			measureHeight(selector) {
				return new Promise(resolve => {
					uni.createSelectorQuery()
						.select(selector)
						.boundingClientRect(data => resolve(data?.height || 0))
						.exec()
				})
			},

			// 加载公司信息
			async loadCompanyInfo() {
				toastload("数据加载中...")
				try {
					const phoneNumber = uni.getStorageSync('phone')

					// 先获取渲染框架
					const res = await getColumns({
						permission: 'admin'
					})
					this.formConfig = res.data

					// 再获取渲染数据
					const comres = await getCompanyInfo({
						phoneNumber
					})
					this.companyForm = comres.data
				} catch (error) {
					console.error('获取公司信息失败:', error)
					toast('获取公司信息失败，请重试')
				} finally {
					closeload()
				}
			},


			// 图片上传相关
			chooseLogoImage(key) {
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'], // 压缩图片
					sourceType: ['album', 'camera'], // 从相册或相机选择
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]; // 获取临时文件路径

						// 读取文件为 Base64
						uni.getFileSystemManager().readFile({
							filePath: tempFilePath,
							encoding: 'base64', // 获取 Base64 数据
							success: (readRes) => {
								// 获取文件后缀（如 png、jpg）
								const fileExt = tempFilePath.split('.').pop().toLowerCase();
								let mimeType = 'image/jpeg'; // 默认 jpeg

								// 根据后缀设置 MIME 类型
								if (fileExt === 'png') mimeType = 'image/png';
								else if (fileExt === 'gif') mimeType = 'image/gif';

								// 拼接成标准的 Data URL（如 ）
								const base64DataUrl = `data:${mimeType};base64,${readRes.data}`;

								// 上传 Base64 数据
								this.uploadLogo(key, tempFilePath, base64DataUrl);
							},
							fail: (readErr) => {
								console.error('读取图片失败:', readErr);
								uni.showToast({
									title: '读取图片失败',
									icon: 'none'
								});
							}
						});
					},
					fail: (err) => {
						console.error('选择图片失败:', err);
						uni.showToast({
							title: '选择图片失败',
							icon: 'none'
						});
					}
				});
			},

			uploadLogo(key, tempFilePath, base64DataUrl) {
				// console.log('文件路径:', tempFilePath);
				// console.log('Base64 Data URL:', base64DataUrl);

				this.uploading = true;

				// 模拟上传
				setTimeout(() => {
					this.uploading = false;

					// 存储到表单数据（包含路径和 Base64）
					this.$set(this.companyForm, key, base64DataUrl);

					uni.showToast({
						title: '上传成功',
						icon: 'success'
					});
				}, 1500);
			},
			deleteLogo(key) {
				showConfirm(`确定删除该图片吗？`).then(res => {
					if (res.confirm) {
						this.$set(this.companyForm, key, '')
					}
				})
			},

			// 标签相关方法
			getArrayFromString(str) {
				return str ? str.split(",").filter(item => item.trim() !== "") : []
			},

			removeTag(key, label, index) {

				showConfirm(`确定删除该${label}吗？`).then(res => {
					if (res.confirm) {
						const arr = this.getArrayFromString(this.companyForm[key])
						arr.splice(index, 1)
						this.$set(this.companyForm, key, arr.join(","))
						toastC("删除成功")
					}
				})
			},

			editTag(index, label, key, value) {
				this.currentTagLabel = label
				this.tagDialogTitle = `编辑${label}`
				this.currentTagKey = key
				this.currentTagValue = value
				this.currentTagIndex = index
				this.showTagDialogVisible = true
			},

			showTagDialog(label, key) {
				this.currentTagLabel = label
				this.tagDialogTitle = `添加${label}`
				this.currentTagKey = key
				this.currentTagValue = ''
				this.currentTagIndex = -1
				this.showTagDialogVisible = true
			},

			saveTag() {
				if (!this.currentTagValue.trim()) {
					toast(`请输入${this.currentTagLabel}`)
					return false
				}

				const targetArray = this.getArrayFromString(this.companyForm[this.currentTagKey])
				const isDuplicate = targetArray.some(
					(item, index) => item === this.currentTagValue && index !== this.currentTagIndex
				)

				if (isDuplicate) {
					toast("该名称已存在，请勿重复添加")
					return false
				}

				if (this.currentTagIndex >= 0) {
					// 编辑
					targetArray.splice(this.currentTagIndex, 1, this.currentTagValue)
				} else {
					// 添加
					targetArray.push(this.currentTagValue)
				}

				this.$set(this.companyForm, this.currentTagKey, targetArray.join(","))
				toast(this.currentTagIndex >= 0 ? '编辑成功' : '添加成功')
				this.resetTagForm()
				return true
			},

			resetTagForm() {
				this.currentTagValue = ''
				this.currentTagIndex = -1
				this.currentTagKey = ''
				this.showTagDialogVisible = false
			},

			// 对象数组相关方法
			showItemDialog(label, key, formConfig) {
				this.itemDialogTitle = `添加${label}`
				this.currentItemKey = key
				this.currentFormConfig = formConfig.map(c => {
					return {
						...c,
						required: c.required === true || c.required === "true"
					}
				})
				this.currentItem = formConfig.reduce((obj, field) => {
					obj[field.key] = ''
					return obj
				}, {})
				this.currentItemIndex = -1
				this.showItemDialogVisible = true
			},

			editItem(index, item, key, label, formConfig) {
				this.itemDialogTitle = `编辑${label}`
				this.currentItemKey = key
				this.currentFormConfig = formConfig.map(c => {
					return {
						...c,
						required: c.required === true || c.required === "true"
					}
				})
				this.currentItem = {
					...item
				}
				this.currentItemIndex = index
				this.showItemDialogVisible = true
			},

			saveItem() {
				// 验证必填字段
				const missingFields = this.currentFormConfig
					.filter(field => field.required && (!this.currentItem[field.key] || this.currentItem[field.key]
						.trim() === ''))
					.map(field => field.label)

				if (missingFields.length > 0) {
					toast(`${missingFields.join('、')}不能为空`, 'none', 2000)
					return false
				}

				const checkDuplicateFields = this.currentFormConfig
					.filter(c => c.required)
					.map(c => c.key);
				const existingItems = this.companyForm[this.currentItemKey] || []

				for (const field of checkDuplicateFields) {
					if (this.currentFormConfig.some(config => config.key === field)) {
						const duplicateIndex = existingItems.findIndex(
							(item, index) =>
							item[field] === this.currentItem[field] &&
							index !== this.currentItemIndex
						)

						if (duplicateIndex >= 0) {
							const fieldConfig = this.currentFormConfig.find(config => config.key === field)
							toast(`${fieldConfig?.label || field}已存在，请勿重复添加`)
							return false
						}
					}
				}

				if (this.currentItemIndex >= 0) {
					// 编辑
					this.$set(this.companyForm[this.currentItemKey], this.currentItemIndex, {
						...this.currentItem
					})
				} else {
					// 添加
					if (!Array.isArray(this.companyForm[this.currentItemKey])) {
						this.$set(this.companyForm, this.currentItemKey, [])
					}
					this.companyForm[this.currentItemKey].push({
						...this.currentItem
					})
				}

				toast(this.itemDialogTitle + '成功')
				this.resetItemForm()
				return true
			},

			resetItemForm() {
				this.currentItem = {}
				this.currentItemIndex = -1
				this.currentItemKey = ''
				this.showItemDialogVisible = false
			},

			showDeleteConfirm(index, label, key) {
				this.deleteConfirmText = `确定删除${label}吗?`
				this.deleteIndex = index
				this.deleteKey = key
				this.showDeleteDialogVisible = true
			},

			confirmDelete() {
				this.companyForm[this.deleteKey].splice(this.deleteIndex, 1)
				this.showDeleteDialogVisible = false
				toastC("删除成功")
			},

			// 保存公司信息
			async saveCompanyInfo() {
				try {
					toastload("保存中...")
					const missingFields = this.formConfig
						.filter(field => field.required && (!this.companyForm[field.key] || this.companyForm[field.key]
							.trim() === ''))
						.map(field => field.label)

					if (missingFields.length > 0) {
						toast(`${missingFields.join('、')}不能为空`, 'none', 2000)
						return
					}
					this.saving = true
					let res = await customerUpdate(this.companyForm)
					toastC(res.msg)
					setTimeout(() => {
						closeload()
						uni.navigateBack()
					}, 1500)
				} catch (error) {
					console.error('保存失败:', error)
					toast('保存失败，请重试')
				} finally {
					this.saving = false
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 120rpx;
	}

	.content {
		padding: 20rpx;
	}

	.section {
		margin-top: 10rpx;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-bottom: 24rpx;

		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			margin-bottom: 30rpx;
			color: #333;
		}
	}

	.img-upload {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 20rpx 0;
		position: relative;

		.img-container {
			width: 200rpx;
			height: 200rpx;
			border-radius: 12rpx;
			background-color: #f9f9f9;
			display: flex;
			justify-content: center;
			align-items: center;
			position: relative;
			overflow: hidden;

			.logo-image {
				width: 100%;
				height: 100%;
			}

			.upload-btn {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				.upload-text {
					margin-top: 10rpx;
					font-size: 24rpx;
					color: #999;
				}
			}

			.upload-mask {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background-color: rgba(0, 0, 0, 0.5);
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.mask-text {
					color: #fff;
					font-size: 24rpx;
					margin-top: 10rpx;
				}
			}
		}

		.img-tip {
			font-size: 24rpx;
			color: #999;
			margin-top: 16rpx;
			text-align: center;
		}

		.delete-icon {
			position: absolute;
			top: 10rpx;
			right: 10rpx;
			background-color: rgba(255, 255, 255, 0.8);
			border-radius: 50%;
			padding: 8rpx;
			z-index: 2;
		}
	}

	/* 标签样式 */
	.tags-container {
		display: flex;
		flex-wrap: wrap;
		align-items: center;

		.tags-list {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			gap: 10rpx;
		}

		.tag-item {
			margin-right: 10rpx;
		}

		.add-tag {
			display: flex;
			align-items: center;
			color: #2979ff;
			font-size: 24rpx;
			padding: 0 10rpx;
			border: 1px solid #2979ff;
			border-radius: 8rpx;
			height: 60rpx;
			margin-top: 10rpx;
		}
	}

	.obj-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.obj-card {
		background-color: #f9f9f9;
		border-radius: 12rpx;
		padding: 24rpx;
		position: relative;

		.obj-content {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;

			.info {
				display: flex;
				flex-direction: column;
				flex: 1;
				line-height: 48rpx;

				.name {
					font-size: 32rpx;
					font-weight: bold;
					margin-bottom: 6rpx;
				}

				.position {
					font-size: 28rpx;
					color: #666;
					margin-bottom: 6rpx;
				}

				.phone {
					font-size: 28rpx;
					color: #666;
					margin-bottom: 6rpx;
				}

				.trainingExperience,
				.remarks {
					font-size: 26rpx;
					color: #888;
					margin-top: 10rpx;
					line-height: 1.4;
				}
			}

			.operate {
				width: 120rpx;
				height: 220rpx;

				.up {
					flex: 1;
					display: flex;
					justify-content: space-between;
				}

				.down {
					position: absolute;
					display: flex;
					align-items: center;
					right: 20rpx;
					bottom: 20rpx;
					color: #666;
					font-size: 20rpx;
				}
			}
		}
	}

	.add-card {
		background-color: #f9f9f9;
		border-radius: 12rpx;
		padding: 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		color: #2979ff;
		font-size: 28rpx;
		border: 1px solid #ccc;

		text {
			margin-top: 10rpx;
		}
	}

	.form {
		padding: 30rpx;
	}

	.numberBox {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.results-scroll {
		padding: 5px 0;
		height: calc(100vh - 180px);
	}

	.footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 20rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);
		padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
		z-index: 100;

		.u-button {
			height: 80rpx;
			font-size: 32rpx;
		}
	}
</style>